<template>
  <el-drawer v-if="visible"
    v-model="visible"
    class="rk-task-drawer"
    size="100%"
    append-to-body
    :show-close="false"
    :with-header="false">
    <div class="rk-task-drawer-container">
      <div class="task-drawer-header"
        flex>
        <div class="task-drawer-header-title">
          <!-- <span class="title-info">评审任务</span> -->
        </div>
        <div class="task-drawer-header-steps"
          flex-col>
          <el-steps :active="stepActive"
            finish-status="success"
            simple>
            <el-step title="基本信息" />
            <el-step title="分配项目" />
            <el-step title="分配专家" />
            <el-step title="挂接规则" />
          </el-steps>
        </div>
        <div class="task-drawer-header-tools"
          flex-col>
          <el-button @click="prevStep"
            :disabled="stepActive <= 0">上一步</el-button>
          <el-button @click="nextStep"
            :disabled="stepActive >= 3">下一步</el-button>
          <el-button @click="saveData"
            :disabled="saveDisable"
            type="primary">保存</el-button>
          <el-button type="danger"
            @click="handleClose">关闭</el-button>
        </div>
      </div>
      <div class="task-drawer-body">
        <keep-alive>
          <task-management-base v-if="stepActive === 0"
            ref="taskManagementBaseRef"
            :taskDetailData="taskDetailData"></task-management-base>
          <task-management-dispatch-proj v-else-if="stepActive == 1"
            ref="taskManagementProjRef"
            :type="type"
            :taskDetailData="taskDetailData"></task-management-dispatch-proj>
          <task-management-dispatch-expert v-else-if="stepActive === 2"
            ref="taskManagementExpertRef"
            :taskDetailData="taskDetailData"></task-management-dispatch-expert>
          <task-mangement-rule v-else-if="stepActive === 3"
            ref="taskManagementRuleRef"
            :taskDetailData="taskDetailData"></task-mangement-rule>
        </keep-alive>
      </div>
    </div>
  </el-drawer>
</template>
  <script setup>
import { ElMessage, ElLoading } from 'element-plus'
import { RkConfirmBox } from '@/components/message-box/index.js'
import TaskManagementBase from './components/TaskManagementBase.vue'
import TaskManagementDispatchProj from './components/TaskManagementDispatchProj.vue'
import TaskManagementDispatchExpert from './components/TaskManagementDispatchExpert.vue'
import TaskMangementRule from './components/TaskMangementRule.vue'
import { reactive, ref } from 'vue'
import { useExpertsApi } from '@/api/index'
const { reviewtaskGetData, reviewtaskSaveData } = useExpertsApi();

const emit = defineEmits(['save'])
const props = defineProps({
})
const stepActive = ref(0)
const saveDisable = ref(true)
const queryParams = reactive({})
const baseFormData = reactive({})
const projectTableData = reactive({})
const expertTableData = reactive({})
const ruleTableData = reactive({})
const taskDetailData = reactive({})
const visible = ref(false)
const taskManagementBaseRef = ref(null)
const taskManagementProjRef = ref(null)
const taskManagementExpertRef = ref(null)
const taskManagementRuleRef = ref(null)
const type = ref(0)
const sendGrandson = function (value) {
  type.value = value
}
provide('sendHandleType', sendGrandson)
// ----- Drawer相关操作
function handleOpen(value) {
  visible.value = true
  stepActive.value = 0
  if (value) { // 修改
    loadFormData(value)
  }
}
//关闭
function handleClose() {
  RkConfirmBox({
    title: '提示',
    content: '关闭后所有未保存的数据将会清空，请谨慎操作！',
    onSubmit: function () {
      handleReset()
    },
    onCancel: function () {
    }
  })
}
//重置
function handleReset() {
  visible.value = false
  stepActive.value = 0
  saveDisable.value = true
  if (taskDetailData.value && taskDetailData.value.taskId) {
    taskDetailData.value.taskId = undefined
  }
  taskManagementBaseRef.value?.resetFormData()
}
// ----- 步进相关操作
function prevStep() {
  if (stepActive.value-- < 0) stepActive.value = 0
  saveDisable.value = !(stepActive.value >= 3)
}
async function nextStep() {
  let nextValid = false
  switch (stepActive.value) {
    case 0:
      const { isBaseValidate, baseForm } = await taskManagementBaseRef.value.getFormData()
      if (isBaseValidate) {
        baseFormData.value = baseForm
        nextValid = true
      } else {
        nextValid = false
        ElMessage.warning('基本信息不能为空！')
      }
      break
    case 1:
      const projectData = taskManagementProjRef.value.getProjectData()
      projectTableData.value = projectData
      if (projectData.isVailde) {
        nextValid = true
      } else {
        nextValid = false
        ElMessage.warning('已分配项目不能为空！')
      }
      break
    case 2:
      const expertData = taskManagementExpertRef.value.getExpertData()
      expertTableData.value = expertData
      if (expertData.isVailde) {
        nextValid = true
      } else {
        nextValid = false
        ElMessage.warning('已分配专家不能为空！')
      }
      break
  }
  if (!nextValid) return
  if (stepActive.value++ > 4) stepActive.value = 0
  saveDisable.value = !(stepActive.value >= 3)
}
// 获取数据
const loadFormData = async (params) => {
  const result = await reviewtaskGetData(params)
  const { code, msg, data } = result
  if (code === 200) {
    taskDetailData.value = data
  } else {
    ElMessage.error(msg ?? '业务失败')
  }
}
//保存数据
const saveData = async () => {
  let addApplyIds = []
  let addExpertIds = []
  let addRuleIds = []
  let delApplyIds = []
  let delExpertIds = []
  let delRuleIds = []
  const { addTableData: projTabData, delTableData: projDelTabData } = projectTableData.value
  projTabData.forEach(element => {
    addApplyIds.push(element.applyId)
  });
  projDelTabData.forEach(element => {
    delApplyIds.push(element.applyId)
  });
  const { addTableData: expertTabData, delTableData: expertDelTabData } = expertTableData.value
  expertTabData.forEach(element => {
    addExpertIds.push(element.expertId)
  });
  expertDelTabData.forEach(element => {
    delExpertIds.push(element.expertId)
  });
  const ruleData = taskManagementRuleRef.value.getRuleData()
  if (!ruleData.isVailde) {
    ElMessage.warning('已分配规则不能为空！')
    return
  }
  ruleTableData.value = ruleData
  const loading = ElLoading.service({ fullscreen: true, text: '信息正在保存中......' })
  const { addTableData: ruleTabData, delTableData: ruleDelTabData } = ruleTableData.value
  ruleTabData.forEach(element => {
    addRuleIds.push(element.pfbzId)
  });
  ruleDelTabData.forEach(element => {
    delRuleIds.push(element.pfbzId)
  });
  queryParams.value = {
    ...queryParams.value,
    ...baseFormData.value,
    addApplyIds: addApplyIds.join(','),
    addExpertIds: addExpertIds.join(','),
    addRuleIds: addRuleIds.join(','),
    delApplyIds: delApplyIds.join(','),
    delExpertIds: delExpertIds.join(','),
    delRuleIds: delRuleIds.join(','),
    taskId: taskDetailData.value?.taskId || ''
  }
  const params = queryParams.value
  const result = await reviewtaskSaveData(params)
  const { code, msg } = result
  if (code === 200) {
    ElMessage.success('保存成功！')
    loading.close()
    handleReset()
    emit('save')
  } else {
    ElMessage.error(msg ?? '业务失败！')
    loading.close()
  }
}
// 对外暴露方法
defineExpose({
  handleOpen
})
</script>
 <style lang="scss" scoped>
.rk-task-drawer-container {
  height: 100%;
  background-color: #f0f2f5;
}
.task-drawer-header {
  width: 100%;
  height: 52px;
  line-height: 52px;
  border-bottom: 1px solid #e8e8e8;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .task-drawer-header-title {
    width: 300px;
    padding-left: 20px;
    .title-info {
      font-size: 16px;
    }
  }
  .task-drawer-header-steps {
    flex: 1;
    line-height: 1;
    padding: 15px 120px 15px 30px;
    .el-steps {
      padding: 0;
      background-color: #fff;
    }
  }
  .task-drawer-header-tools {
    text-align: right;
    width: 330px;
    padding-right: 20px;
  }
}
.task-drawer-body {
  background-color: #fff;
  height: calc(100vh - 52px);
}
</style>
<style lang="scss">
.rk-task-drawer {
  .el-drawer__body {
    padding: 0;
  }
}
</style>